var mysql  = require('mysql');
var dbConfig = require("../db_connection/dbConfig");
var connection = dbConfig.getConnection();

global.CURRENT_USER_GROUP_ID = 1;
global.CURRENT_USER_GROUP_NAME = "Manager";

global.roles = {};

module.exports.loadAccessRights = function(){
	console.log("LOAD ACCESS RIGHTS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    var query = connection.query("select * from user_group", function(err, userGroups)
        {
	          if (err){
	              console.log("Error searching : %s ",err );
	          }else{
	        	  console.log("IS HERE????" + userGroups.length);
	        	  for(var i = 0; i < userGroups.length; i++){
	        		  exports.setUserPermissions(userGroups[i].id, userGroups[i].name);
	        	  }
	          }
        });
}

module.exports.setUserPermissions = function(userGroupId, userGroupName){
	console.log("USER GROUP ID....." + userGroupId);
	console.log("USER GROUP NAME....." + userGroupName);
    var groupPermissions = connection.query("select * from user_group_permission where user_group_id = " + userGroupId + " limit 1", function(_err, permissions)
            {
    	          if (_err){
    	              console.log("Error searching : %s ",_err );
    	          }else{
    	        	  console.log("\n\nUSER PERMISSIONS FOR " + userGroupName);
    	        	  
    	        	  if(permissions.length > 0){
    	        		  global.roles[userGroupId] = {};
    	        		  global.roles[userGroupName] = {};
    	        		  for(var role_name in permissions[0]){
    	        		    	//var role = permissions[userGroupId][ctr];
    	        		    	
    	        		    	if(role_name.indexOf("can_") == 0 || role_name.indexOf("has_") == 0 ){
    	        		    		var HAS_ACCESS = false;
    	        		    		
    	        		    		global.roles[userGroupId][role_name] = {};
    	        		    		global.roles[userGroupName][role_name] = {}
    	        		    		
    	        		    		if(permissions[0][role_name] == 1){
    	        		    			HAS_ACCESS = true;
    	        		    		}
    	        		    		
    	        		    		global.roles[userGroupId][role_name] = HAS_ACCESS;
	        		    			global.roles[userGroupName][role_name] = HAS_ACCESS;
	        		    			
    	        		    		//console.log(role_name + "  :  " + HAS_ACCESS);
    	        		    	}
    	        		    	
    	        		    }
    	        		  
     	        	  }
    	          }
            }
    	);
}
